import { defineStore } from "pinia";
import { reqLogin, reqUserInfo } from "../../api/user";
import {
  loginForm,
  loginResponseForm,
  logoutResponseForm,
  userInfoResponseForm,
} from "../../api/user/type";
import userState from "./types/type";
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from "../../utils/token";
import { constantRoutes, asyncRoute, anyRoute } from "../../router/routes";
import filterAsyncRoutes from "../../utils/filterRoutes";
import { cloneDeep } from "lodash";
import router from "../../router";

let useUserStore = defineStore("User", {
  state: (): userState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoutes,
      username: "",
      avatar: "",
      buttons: [],
    };
  },
  actions: {
    async login(data: loginForm) {
      let result: loginResponseForm = await reqLogin(data);
      if (result.code === 200) {
        SET_TOKEN(result.data as string);
        this.token = result.data as string;
        // console.log(localStorage.getItem("token"));
        return "ok";
      } else {
        return Promise.reject(new Error(result.message as string));
      }
    },
    async userInfo() {
      let result: userInfoResponseForm = await reqUserInfo();
      if (result.code === 200) {
        this.username = result.data.name;
        this.avatar = result.data.avatar;
        this.buttons = result.data.buttons;
        // console.log(this.buttons);
        let newRoutes = filterAsyncRoutes(
          result.data.routes,
          cloneDeep(asyncRoute)
        );
        // console.log(newRoutes);
        this.menuRoutes = [...constantRoutes, ...newRoutes, anyRoute];
        // console.log(result.data.routes);
        // $router.addRoute([...newRoutes, anyRoute] as any);
        [...newRoutes, anyRoute].forEach((route: any) => {
          router.addRoute(route);
        });
        return "ok";
      } else {
        return Promise.reject(new Error(result.message as string));
      }
      // console.log(result);
    },
    userLogout() {
      this.token = "";
      this.username = "";
      this.avatar = "";
      REMOVE_TOKEN();
      this.menuRoutes = constantRoutes;
      // 重新初始化路由
      asyncRoute.forEach((item: any) => {
        if (router.hasRoute(item.name)) {
          // console.log(true);
          router.removeRoute(item.name);
        }
      });
      router.removeRoute("any");
      // console.log(router.hasRoute("Permission"));
    },
  },
  getters: {},
});

export default useUserStore;
